import 'dart:io';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:xiaofanshu_flutter/controller/home_controller.dart';
import 'package:xiaofanshu_flutter/pages/home/index/index.dart';
import 'package:xiaofanshu_flutter/pages/home/message/recently_message.dart';
import 'package:xiaofanshu_flutter/pages/home/mine/mine.dart';
import 'package:xiaofanshu_flutter/pages/home/story/map_page.dart';
import 'package:xiaofanshu_flutter/static/custom_string.dart';
import 'package:badges/badges.dart' as badges;
import 'package:xiaofanshu_flutter/utils/permission_apply.dart';
import '../../static/custom_color.dart';
import 'package:xiaofanshu_flutter/utils/guide_service.dart';
import 'package:xiaofanshu_flutter/utils/guide_debug_helper.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  HomeController homeController = Get.find();
  // 修改：调整页面顺序 - 地图钉第一位，列表第二位
  List<Widget> pages = const [
    MapPage(),      // 0: 故事钉（地图）
    IndexPage(),    // 1: 列表（原首页）
    Text('发布'),   // 2: 发布
    RecentlyMessage(), // 3: 消息
    MinePage(),     // 4: 我的
  ];

  // 引导相关
  GuideController? _guideController;
  bool _hasShownWelcomeGuide = false;

  @override
  void initState() {
    super.initState();
    
    // ========== 修改：简化查找逻辑 ==========
    // GuideController 应该已经在 main.dart 中创建了
    try {
      _guideController = Get.find<GuideController>();
      Get.log('✅ HomePage 找到 GuideController');
    } catch (e) {
      Get.log('❌ HomePage 找不到 GuideController: $e');
      // 作为后备方案，创建一个
      _guideController = Get.put(GuideController(), permanent: true);
      Get.log('✅ HomePage 创建了新的 GuideController');
    }
    // =====================================
    
    // 延迟显示欢迎引导
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _showWelcomeGuideIfNeeded();
    });
  }

  // 显示欢迎引导
  Future<void> _showWelcomeGuideIfNeeded() async {
    if (_hasShownWelcomeGuide) return;
    
    try {
      // 检查是否需要显示引导
      bool isGuideCompleted = await GuideService.isGuideCompleted();
      
      // 只在引导未完成时显示欢迎对话框
      if (!isGuideCompleted && mounted) {
        _hasShownWelcomeGuide = true;
        
        // ========== 等待页面加载动画结束 ==========
        Get.log('⏳ 等待页面加载动画结束...');
        
        // 等待初始延迟
        await Future.delayed(const Duration(milliseconds: 3800));
        
        // 持续检查 LoadingUtil 是否关闭，最多等待 5 秒
        int waitCount = 0;
        const maxWaitCount = 25; // 25 * 200ms = 5秒
        
        while ((Get.isDialogOpen ?? false) && waitCount < maxWaitCount) {
          Get.log('⏳ 检测到对话框打开，继续等待... (${waitCount + 1}/$maxWaitCount)');
          await Future.delayed(const Duration(milliseconds: 200));
          waitCount++;
        }
        
        if (waitCount >= maxWaitCount) {
          Get.log('⚠️ 等待超时，强制显示欢迎引导');
        } else if (waitCount > 0) {
          Get.log('✅ 加载动画已结束，显示欢迎引导');
        }
        
        // 再等待一小段时间确保对话框完全关闭
        await Future.delayed(const Duration(milliseconds: 300));
        // ==========================================
        
        if (!mounted) return;
        await _showWelcomeDialog();
        
        Get.log('✅ 欢迎引导对话框已显示');
      } else {
        Get.log('⏭️ 引导已完成，跳过欢迎对话框');
      }
    } catch (e) {
      Get.log('❌ Error showing welcome guide: $e');
    }
  }

  // 显示欢迎对话框
  Future<void> _showWelcomeDialog() async {
    return showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => AlertDialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(20),
        ),
        title: Row(
          children: [
            Container(
              padding: const EdgeInsets.all(8),
              decoration: BoxDecoration(
                color: const Color(0xFF6366F1).withOpacity(0.1),
                borderRadius: BorderRadius.circular(12),
              ),
              child: const Icon(
                Icons.waving_hand,
                color: Color(0xFF6366F1),
                size: 28,
              ),
            ),
            const SizedBox(width: 12),
            const Expanded(
              child: Text(
                '欢迎来到故事地图',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ],
        ),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              '这是您第一次使用我们的应用！',
              style: TextStyle(
                fontSize: 15,
                color: Color(0xFF6B7280),
              ),
            ),
            const SizedBox(height: 12),
            const Text(
              '让我们花一分钟时间，为您介绍主要功能：',
              style: TextStyle(
                fontSize: 14,
                color: Color(0xFF6B7280),
              ),
            ),
            const SizedBox(height: 16),
            _buildFeatureItem(Icons.home, '浏览精彩故事'),
            _buildFeatureItem(Icons.map, '在地图上探索'),
            _buildFeatureItem(Icons.person, '与故事AI主角互动'),
            _buildFeatureItem(Icons.message, '与好友聊天互动'),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () {
              Get.back();
              _skipAllGuides();
            },
            child: const Text(
              '跳过',
              style: TextStyle(color: Color(0xFF9CA3AF)),
            ),
          ),
          ElevatedButton(
            onPressed: () {
              Get.back();
              _startGuideTour();
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: const Color(0xFF6366F1),
              foregroundColor: Colors.white,
              padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12),
              ),
            ),
            child: const Text(
              '开始引导',
              style: TextStyle(fontSize: 15, fontWeight: FontWeight.w600),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildFeatureItem(IconData icon, String text) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: Row(
        children: [
          Icon(icon, size: 20, color: const Color(0xFF6366F1)),
          const SizedBox(width: 12),
          Text(
            text,
            style: const TextStyle(fontSize: 14, color: Color(0xFF374151)),
          ),
        ],
      ),
    );
  }

  // 开始引导流程
  void _startGuideTour() async {
    // 修改：先显示故事钉页面的引导，再显示列表页的引导
    
    // 确保在故事钉页面（现在是 index 0）
    if (homeController.currentIndex.value != 0) {
      homeController.changeIndex(0);
      // 等待页面切换完成
      await Future.delayed(const Duration(milliseconds: 300));
    }
    
    // 通知 GuideController 开始引导流程
    if (_guideController != null) {
      Get.log('🎯 开始引导流程 - 从故事钉页面开始');
      
      // 延迟一下，确保 MapPage 已经构建完成
      await Future.delayed(const Duration(milliseconds: 800));
      
      // 触发 MapPage 的引导（故事钉）
      _guideController!.triggerMapGuide();
      
      Get.log('✅ 已触发 MapPage 引导（故事钉）');
    }
  }

  // 跳过所有引导
  Future<void> _skipAllGuides() async {
    await GuideService.setGuideCompleted();
    _guideController?.completeAllGuides();
    
    Get.snackbar(
      '已跳过引导',
      '您可以在设置中重新查看新手引导',
      snackPosition: SnackPosition.BOTTOM,
      duration: const Duration(seconds: 2),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Obx(() => pages[homeController.currentIndex.value]),
      // =====================================
      bottomNavigationBar: Obx(
        () => BottomNavigationBar(
          backgroundColor: Colors.white,
          type: BottomNavigationBarType.fixed,
          elevation: 3,
          selectedFontSize: 0,
          unselectedFontSize: 0,
          showSelectedLabels: false,
          showUnselectedLabels: false,
          items: [
            // 修改：调整顺序 - 故事钉第一位
            const BottomNavigationBarItem(
                icon: Text(HomeTabName.shopping,
                    style: TextStyle(
                      fontSize: 16,
                      color: CustomColor.unselectedColor,
                    )),
                activeIcon: Text(HomeTabName.shopping,
                    style: TextStyle(
                      fontSize: 22,
                      color: Color(0xff2b2b2b),
                    )),
                label: HomeTabName.shopping),
            // 列表第二位
            const BottomNavigationBarItem(
                icon: Text(HomeTabName.index,
                    style: TextStyle(
                      fontSize: 16,
                      color: CustomColor.unselectedColor,
                    )),
                activeIcon: Text(HomeTabName.index,
                    style: TextStyle(
                      fontSize: 22,
                      color: Color(0xff2b2b2b),
                    )),
                label: HomeTabName.index),
            BottomNavigationBarItem(
                icon: IconButton(
                  splashColor: Colors.transparent,
                  highlightColor: Colors.transparent,
                  onPressed: () async {
                    // 选择发布图文还是视频
                    Get.bottomSheet(
                      SizedBox(
                        height: 220,
                        width: double.infinity,
                        child: Column(
                          children: [
                            GestureDetector(
                              onTap: () async {
                                Get.back();
                                
                                // 申请照片权限
                                bool hasPermission = await PermissionApply.requestPhotosPermission();
                                if (!hasPermission) {
                                  Get.snackbar(
                                    '权限提示',
                                    '需要照片权限才能选择图片',
                                    snackPosition: SnackPosition.BOTTOM,
                                  );
                                  return;
                                }
                                
                                List<AssetEntity>? result =
                                    await AssetPicker.pickAssets(
                                  context,
                                  pickerConfig: const AssetPickerConfig(
                                    maxAssets: 9,
                                    requestType: RequestType.image,
                                  ),
                                );
                                if (result != null && result.isNotEmpty) {
                                  List<File> files = [];
                                  for (var asset in result) {
                                    File? file = await asset.originFile;
                                    if (file != null) {
                                      files.add(file);
                                    }
                                  }
                                  Get.toNamed(
                                    '/publish/notes',
                                    arguments: {
                                      'type': 0,
                                      'files': files,
                                    },
                                  );
                                }
                              },
                              child: Container(
                                height: 50,
                                width: double.infinity,
                                decoration: const BoxDecoration(
                                  color: Colors.white,
                                  border: Border(
                                    bottom: BorderSide(
                                      color: Color(0xffe5e5e5),
                                      width: 0.5,
                                    ),
                                  ),
                                ),
                                child: const Center(
                                  child: Text(
                                    '图文故事',
                                    textAlign: TextAlign.center,
                                    style: TextStyle(
                                      fontSize: 16,
                                    ),
                                  ),
                                ),
                              ),
                            ),
                            GestureDetector(
                              onTap: () async {
                                Get.back();
                                
                                // 申请视频权限
                                bool hasPermission = await PermissionApply.requestVideosPermission();
                                if (!hasPermission) {
                                  Get.snackbar(
                                    '权限提示',
                                    '需要视频权限才能选择视频',
                                    snackPosition: SnackPosition.BOTTOM,
                                  );
                                  return;
                                }
                                
                                List<AssetEntity>? results =
                                    await AssetPicker.pickAssets(
                                  context,
                                  permissionRequestOption:
                                      const PermissionRequestOption(
                                    androidPermission: AndroidPermission(
                                        type: RequestType.video,
                                        mediaLocation: true),
                                  ),
                                  pickerConfig: const AssetPickerConfig(
                                    maxAssets: 1,
                                    requestType: RequestType.video,
                                  ),
                                );
                                if (results != null && results.isNotEmpty) {
                                  AssetEntity asset = results.first;
                                  File? file = await asset.originFile;
                                  if (file != null) {
                                    Get.toNamed(
                                      '/video/clip',
                                      arguments: {
                                        'file': file,
                                        'aspectRatio':
                                            asset.height / asset.width,
                                      },
                                    );
                                  }
                                }
                              },
                              child: Container(
                                height: 50,
                                width: double.infinity,
                                decoration: const BoxDecoration(
                                  color: Colors.white,
                                  border: Border(
                                    bottom: BorderSide(
                                      color: Color(0xffe5e5e5),
                                      width: 0.5,
                                    ),
                                  ),
                                ),
                                child: const Center(
                                  child: Text(
                                    '视频故事',
                                    textAlign: TextAlign.center,
                                    style: TextStyle(
                                      fontSize: 16,
                                    ),
                                  ),
                                ),
                              ),
                            ),
                            GestureDetector(
                              onTap: () {
                                Get.back();
                                Get.toNamed('/story/route/map');
                              },
                              child: Container(
                                height: 50,
                                width: double.infinity,
                                decoration: const BoxDecoration(
                                  color: Colors.white,
                                  border: Border(
                                    bottom: BorderSide(
                                      color: Color(0xffe5e5e5),
                                      width: 0.5,
                                    ),
                                  ),
                                ),
                                child: const Center(
                                  child: Text(
                                    '发故事路线',
                                    textAlign: TextAlign.center,
                                    style: TextStyle(
                                      fontSize: 16,
                                    ),
                                  ),
                                ),
                              ),
                            ),
                            const SizedBox(
                              height: 10,
                            ),
                            GestureDetector(
                              onTap: () {
                                Get.back();
                              },
                              child: Container(
                                height: 50,
                                width: double.infinity,
                                decoration: const BoxDecoration(
                                  color: Colors.white,
                                  border: Border(
                                    bottom: BorderSide(
                                      color: Color(0xffe5e5e5),
                                      width: 0.5,
                                    ),
                                  ),
                                ),
                                child: const Center(
                                  child: Text(
                                    '取消',
                                    textAlign: TextAlign.center,
                                    style: TextStyle(
                                      fontSize: 16,
                                    ),
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    );
                  },
                  icon: Center(
                    child: Container(
                      width: 55,
                      height: 40,
                      decoration: BoxDecoration(
                        color: CustomColor.primaryColor,
                        borderRadius: BorderRadius.circular(12),
                      ),
                      child: const Icon(
                        Icons.add,
                        color: Colors.white,
                        size: 30,
                      ),
                    ),
                  ),
                ),
                label: HomeTabName.release),
            BottomNavigationBarItem(
              icon: homeController.unReadCount.value == 0
                  ? const Text(HomeTabName.message,
                      style: TextStyle(
                        fontSize: 16,
                        color: CustomColor.unselectedColor,
                      ))
                  : badges.Badge(
                      badgeContent: Text(
                        homeController.unReadCount.value.toString(),
                        style: const TextStyle(
                          color: Colors.white,
                          fontSize: 10,
                        ),
                      ),
                      badgeAnimation: const badges.BadgeAnimation.scale(),
                      child: const Text(HomeTabName.message,
                          style: TextStyle(
                            fontSize: 16,
                            color: CustomColor.unselectedColor,
                          )),
                    ),
              activeIcon: homeController.unReadCount.value == 0
                  ? const Text(HomeTabName.message,
                      style: TextStyle(
                        fontSize: 22,
                        color: Color(0xff2b2b2b),
                      ))
                  : badges.Badge(
                      badgeContent: Text(
                        homeController.unReadCount.value.toString(),
                        style: const TextStyle(
                          color: Colors.white,
                          fontSize: 10,
                        ),
                      ),
                      badgeAnimation: const badges.BadgeAnimation.scale(),
                      child: const Text(HomeTabName.message,
                          style: TextStyle(
                            fontSize: 22,
                            color: Color(0xff2b2b2b),
                          )),
                    ),
              label: HomeTabName.message,
            ),
            const BottomNavigationBarItem(
                icon: Text(HomeTabName.mine,
                    style: TextStyle(
                      fontSize: 16,
                      color: CustomColor.unselectedColor,
                    )),
                activeIcon: Text(HomeTabName.mine,
                    style: TextStyle(
                      fontSize: 22,
                      color: Color(0xff2b2b2b),
                    )),
                label: HomeTabName.mine),
          ],
          currentIndex: homeController.currentIndex.value,
          onTap: homeController.changeIndex,
        ),
      ),
    );
  }
}
